﻿/*
=======================================================
    Permission【权限】
=======================================================
*/

namespace Services
{
    public interface IPermissionLogic : ILogic<PermissionModel, PermissionFilterModel>
    {
        List<PermissionModel> GetTreePermission();
        List<PermissionModel> GetTreePermissionByRegulator();
    }


    public class PermissionLogic : BaseLogic<PermissionModel, PermissionFilterModel, Permission, IPermissionRepository, IPermissionMapping, IPermissionService>, IPermissionLogic
    {
        private readonly IRolePermissionRepository _IRolePermissionRepository;

        public PermissionLogic(ICurrentUser currentUser, IPermissionRepository repository, IPermissionMapping mapping, IPermissionService service,
            IRolePermissionRepository iRolePermissionRepository)
            : base(currentUser, repository, mapping, service)
        {
            _IRolePermissionRepository = iRolePermissionRepository;
        }

        #region 获取所有权限的树形结构数据
        public List<PermissionModel> GetTreePermission()
        {
            //得到所有权限数据
            var list = GetAll().ToList();

            var res_list = list.Where(x => x.ParentID == 0).OrderByDescending(x => x.SortNo).ToList();

            foreach (var lv1 in res_list)
            {
                lv1.Lv = "lv1";
                var lv2_list = list.Where(x => x.ParentID == lv1.PerID).OrderByDescending(x => x.SortNo).ToList();

                foreach (var lv2 in lv2_list)
                {
                    lv2.Lv = "lv2";
                    lv2.Children.AddRange(list.Where(x => x.ParentID == lv2.PerID).OrderByDescending(x => x.SortNo));
                }

                lv1.Children.AddRange(lv2_list);
            }

            return res_list;
        }
        #endregion

        #region 获取所有监管部门权限的树形结构数据
        public List<PermissionModel> GetTreePermissionByRegulator()
        {
            var list = _mapping.Entity2Model(_repository.GetTreePermissionByRegulator());

            var res_list = list.Where(x => x.ParentID == 0).OrderByDescending(x => x.SortNo).ToList();

            foreach (var lv1 in res_list)
            {
                lv1.Lv = "lv1";
                var lv2_list = list.Where(x => x.ParentID == lv1.PerID).OrderByDescending(x => x.SortNo).ToList();

                foreach (var lv2 in lv2_list)
                {
                    lv2.Lv = "lv2";
                    lv2.Children.AddRange(list.Where(x => x.ParentID == lv2.PerID).OrderByDescending(x => x.SortNo));
                }

                lv1.Children.AddRange(lv2_list);
            }

            return res_list;
        } 
        #endregion
    }
}
